<template>
  <div>
    <a-form-model
      ref="formModel"
      :model="form"
      layout="inline"
      class="search-form"
      :rules="formRules"
    >
    <div class="search-box">
      <a-form-model-item
        class="search-item"
        prop="name"
        label="维护人员"
      >
        <a-input
          autocomplete="off"
          v-model="form.name"
        ></a-input>
      </a-form-model-item>
      <a-form-model-item
        class="search-item"
        prop="resultType"
        label="事件结果"
      >
        <a-select
          :getPopupContainer="
            triggerNode => {
              return triggerNode.parentNode || document.body;
            }"
          v-model="form.resultType">
          <a-select-option value=''>全部</a-select-option>
          <a-select-option value='1'>成功</a-select-option>
          <a-select-option value='0'>失败</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item
        class="search-item"
        prop="ip"
        label="IP"
      >
        <a-input
          autocomplete="off"
          v-model="form.ip"
        ></a-input>
      </a-form-model-item>
      <a-form-model-item
        class="search-item"
        prop="type"
        label="操作类型"
      >
        <a-select
          :getPopupContainer="
            triggerNode => {
              return triggerNode.parentNode || document.body;
            }"
          v-model="form.type">
          <a-select-option
            v-for="(d, i) in actionTypeMap"
            :key="d.key + '_' + i"
            :value="d.key"
          >{{ d.label }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item
        class="search-item"
        prop="sortType"
        label="排序"
      >
        <a-select
          :getPopupContainer="
            triggerNode => {
              return triggerNode.parentNode || document.body;
            }"
          v-model="form.sortType">
          <a-select-option
            v-for="(d, i) in sortMap"
            :key="i"
            :value="i"
          >{{ d }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item
        class="search-item"
        prop="dateRange"
        label="请求时间"
      >
        <a-range-picker
          v-model="form.dateRange"
          inputReadOnly
          :placeholder="['开始时间', '结束时间']"
          :disabled-date="disabledDate"
          format="YYYY/MM/DD HH:mm:ss"
          :show-time="true"
        />
      </a-form-model-item>
      <div :style="btnWrapperStyle" class="search-item">
        <a-button
          type="primary"
          @click="loadData(true)"
          icon="search"
          style="margin-left: 12px"
        >查询</a-button>
        <a-button
          @click="resetSearchForm"
          icon="reload"
          style="margin-left: 12px"
        >重置</a-button>
        <a-button
          v-if="hasPermission('SysLogResume')"
          type="primary"
          @click="recoveryLog"
          style="margin-left: 24px"
        >恢复</a-button>
        <a-button
          v-if="hasPermission('sysLogBackup')"
          type="primary"
          @click="backupLog"
          style="margin-left: 12px"
        >备份</a-button>
        <div
          v-if="hasPermission('SysLogDelete')"
          style="display: inline-block;margin-left: 12px;"
        >
          <a-popconfirm title="确定删除吗?" @confirm="() => deleteLog">
            <a-button type="primary">删除</a-button>
          </a-popconfirm>
          <div style="color: rgba(0, 0, 0, 0.45);line-height: 16px;">
            只删除六个月之前的业务日志
          </div>
        </div>
      </div>
    </div>
      <!-- <a-row class="search-tool-row">
        <a-col :span="5">
          <a-form-model-item
            prop="name"
            label="维护人员"
          >
            <a-input
              autocomplete="off"
              v-model="form.name"
              :allowClear="false"
            ></a-input>
          </a-form-model-item>
        </a-col>

        <a-col :span="5">
          <a-form-model-item
            prop="resultType"
            label="事件结果"
          >
            <a-select v-model="form.resultType">
              <a-select-option value=''>全部</a-select-option>
              <a-select-option value='1'>成功</a-select-option>
              <a-select-option value='0'>失败</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :span="5">
          <a-form-model-item
            prop="ip"
            label="IP"
          >
            <a-input
              autocomplete="off"
              v-model="form.ip"
              :allowClear="false"
            ></a-input>
          </a-form-model-item>
        </a-col>

        <a-col :span="8">
          <a-form-model-item
            prop="dateRange"
            label="请求时间"
          >
            <a-range-picker
              v-model="form.dateRange"
              inputReadOnly
              :placeholder="['开始时间', '结束时间']"
              :disabled-date="disabledDate"
              format="YYYY/MM/DD HH:mm:ss"
              :show-time="true"
            />
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row class="search-tool-row">
        <a-col :span="5">
          <a-form-model-item
            prop="type"
            label="操作类型"
          >
            <a-select v-model="form.type">
              <a-select-option
                v-for="(d, i) in actionTypeMap"
                :key="d.key + '_' + i"
                :value="d.key"
              >{{ d.label }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :span="5">
          <a-form-model-item
            prop="sortType"
            label="排序"
          >
            <a-select v-model="form.sortType">
              <a-select-option
                v-for="(d, i) in sortMap"
                :key="i"
                :value="i"
              >{{ d }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="10"  class="flex-reverse">
          <div style="line-height: 40px;">
            <a-button
              type="primary"
              @click="loadData(true)"
              icon="search"
              style="margin-left: 12px"
            >查询</a-button>
            <a-button
              @click="resetSearchForm"
              icon="reload"
              style="margin-left: 12px"
            >重置</a-button>
            <a-button
              v-if="hasPermission('SysLogResume')"
              type="primary"
              @click="recoveryLog"
              style="margin-left: 24px"
            >恢复</a-button>
            <a-button
              v-if="hasPermission('sysLogBackup')"
              type="primary"
              @click="backupLog"
              style="margin-left: 12px"
            >备份</a-button>
            <a-button
              v-if="hasPermission('sysLogDelete')"
              type="primary"
              @click="deleteLog"
              style="margin-left: 12px"
            >删除</a-button>
          </div>
        </a-col>
      </a-row> -->
    </a-form-model>

    <a-table
      ref="table"
      rowKey="id"
      size="middle"
      :columns="columns"
      :dataSource="gDataSource"
      :pagination="gPagination"
      @change="gHandleTableChange"
    >
      <span
        slot="sortCol"
        slot-scope="text, record, index"
      >
        {{
          (gPagination.current - 1) * gPagination.pageSize + parseInt(index) + 1
        }}
      </span>
      <a-tooltip
        slot="logContent"
        slot-scope="text"
        placement="topLeft"
        :title="text"
      >
        <span>{{ text }}</span>
      </a-tooltip>
    </a-table>
  </div>
</template>

<script>
  import moment from 'moment';
  import { GwListMixin } from "@/mixins/GwListMixin";
  import { getAction } from "@/api/manage";
  import { hasRight, stringSp } from "@/utils/util";

  export default {
    name: "BusinessLog",
    mixins: [GwListMixin],
    data() {
      return {
        // 表头
        columns: [
        {
          title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 50,
          align: "center",
          scopedSlots: { customRender: "sortCol" },
        },
        {
          title: "请求时间",
          dataIndex: "createTime",
          width: 100,
        },
        {
          title: "维护人员",
          dataIndex: "username",
          width: 50,
        },
        {
          title: "IP",
          dataIndex: "ip",
          width: 80,
        },
        {
          title: "事件类型",
          dataIndex: "type",
          width: 50,
          customRender: (text) => '业务',
        },
        {
          title: "日志内容",
          dataIndex: "logContent",
          ellipsis: true,
          scopedSlots: { customRender: 'logContent' },
          width: 200,
        },
        {
          title: "操作类型",
          dataIndex: "operateTypeName",
          width: 50,
        },
        {
          title: "事件结果",
          dataIndex: "statusName",
          width: 50,
        }, ],
        formRules: {
          name: [{
            validator: this.validators.noWhitespace(),
            trigger: 'change'
          },
          {
            validator: this.validators.noIllegalString(),
            trigger: 'change'
          },
          {
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'change'
          }, ],
          logContent: [{
            validator: this.validators.noWhitespace(),
            trigger: 'change'
          },
          {
            validator: this.validators.noIllegalString(),
            trigger: 'change'
          },
          {
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'change'
          }, ],
          ip: [{
            validator: this.validators.noWhitespace(),
            validator: this.validators.isValidIp(),
            trigger: 'change'
          }, ],
          dateRange: [{ validator: this.validators.datetimeValidator() }]
        },
        resultMap: ['全部', '成功', '失败'],
        actionTypeMap: [{ key: '', label: '全部' }],
        sortMap: [
          '时间降序',
          '时间升序',
          'IP降序',
          'IP升序',
          '用户名降序',
          '用户名升序',
          '操作类型降序',
          '操作类型升序'
        ],
        form: {
          dateRange: [],
          name: "",
          logContent: "",
          ip: "",
          type: '',
          resultType: '',
          sortType: 0,
        },
        btnWrapperStyle: {
          'display': 'flex',
          'position': 'relative',
          'top': '5px',
        }
      };
    },
    mounted() {
      this.gQueryParam.excludeOperateType = ['5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '27']
      this.loadData()
      this.loadActionTypeList()
    },
    methods: {
      hasPermission(code) {
        return hasRight(code);
      },
      subText(str, len) {
        return stringSp(str, len);
      },
      disabledDate(current) {
        // Can not select days before today and today
        return current && current > moment().endOf('day');
      },
      loadData(isDoSearch) {
        if (this.form.type !== '') {
          this.gQueryParam.operateType = [this.form.type]
        } else {
          this.gQueryParam.operateType = ''
        }
        this.gQueryParam.username = this.form.name
        this.gQueryParam.ip = this.form.ip
        this.gQueryParam.logContent = this.form.logContent
        this.gQueryParam.status = this.form.resultType
        this.gQueryParam.orderType = this.form.sortType
        this.gQueryParam.startTime = this.form.dateRange.length > 0 ? this.form.dateRange[0].format('YYYY/MM/DD HH:mm:ss') : ''
        this.gQueryParam.endTime = this.form.dateRange.length > 0 ? this.form.dateRange[1].format('YYYY/MM/DD HH:mm:ss') : ''
        this.$refs.formModel.validate(error => {
          if (!error) { return }
          if (isDoSearch) {
            this.gQueryParam.pageNo = 1
            this.gPagination.current = 1
          }
          this.gQueryParam.title = '业务日志'
          getAction('/sys/log/list', this.gQueryParam).then((res) => {
            if (res.success) {
              this.gDataSource = res.result.records
              this.gPagination.total = res.result.total
            }
          })
        })
      },
      loadActionTypeList() {
        this.actionTypeMap = [{ key: '', label: '全部' }]
        const postData = {
          isSystem: false,
          excludeOperateType: this.gQueryParam.excludeOperateType,
          title: "系统管理-系统日志-业务日志"
        }

        getAction('/sys/log/operate_type_list', postData).then((res) => {
          if (res.success) {
            this.actionTypeMap = this.actionTypeMap.concat(res.result.map(item => {
              return {
                key: item.value,
                label: item.name,
              }
            }))
          }
        })
      },
      recoveryLog() {
        this.gQueryParam.orderType = 1
        getAction('/sys/log/resume', this.gQueryParam).then((res) => {
          if (res.success) {
            this.$message.success('操作成功')
          }
        })
      },
      backupLog() {
        this.gQueryParam.orderType = 1
        getAction('/sys/log/backup', this.gQueryParam).then((res) => {
          if (res.success) {
            this.$message.success('操作成功')
          }
        })
      },
      deleteLog() {
        this.gQueryParam.orderType = 1
        getAction('/sys/log/deleteLogs', this.gQueryParam).then((res) => {
          if (res.success) {
            this.$message.success('操作成功')
          }
        })
      },
      resetSearchForm() {
        this.form.dateRange = []
        this.form.name = ""
        this.form.logContent = ""
        this.form.ip = ""
        this.form.type = ''
        this.form.resultType = ''
        this.form.sortType = 0
        this.$refs.formModel.resetFields()
      },
    },
  };
</script>

<style
  lang="less"
  scoped
>
  .search-form {
    margin-bottom: 18px;
    display: block;

    /deep/ .ant-form-item .ant-form-item-label {
      min-width: 80px;
    }

    /deep/ .ant-form-item-control-wrapper {
      min-width: 184px;
    }
    /* .flex-reverse{
      display: flex;
      flex-direction: column-reverse;
    } */
    .search-box {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-wrap: wrap;
      .search-item{
        padding: 0 22px 6px 0;
        min-width: 360px;
      }
    }
    /deep/ .ant-form-inline .ant-form-item {
      margin: 0;
    }
  }

  .search-tool-row {
    display: flex;
    justify-content: flex-start;

    &:first-child {
      margin-bottom: 14px;
    }
  }
</style>
